import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

class Solution03 {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            hashMap.put(nums[i], hashMap.getOrDefault(nums[i], 0) + 1);
        }
        // 创建大根堆
        PriorityQueue<Map.Entry<Integer, Integer>> q = new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());
        for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
            q.offer(entry);
            if (q.size() > k) {
                q.poll();
            }
        }
        //储存结果
        int[] ret = new int[k];
        for (int i = 0; i < k; i++) {
            ret[i] = q.poll().getKey();
        }
        return ret;
    }
}